﻿using System.IO;
using System.Linq;
using System.Xml.Linq;
using Mono.Cecil;

namespace ResourceManager
{
    public static class CecilExtensions
    {
        public static TResource Find<TResource>(this ResourceCollection @this, string name)
            where TResource : Resource
        {
            return (TResource)@this.Cast<Resource>().Where(x => x.Name == name).Single();
        }

        public static EmbeddedResource FindEmbeddedResource(this ResourceCollection @this, string name)
        {
            return @this.Find<EmbeddedResource>(name);
        }

        public static string GetText(this byte[] @this)
        {
            var text = string.Empty;
            using (var stream = new MemoryStream(@this))
            {
                using (var reader = new StreamReader(stream))
                {
                    text = reader.ReadToEnd();
                    reader.Close();
                }
                stream.Close();
            }
            return text;
        }

        public static XElement GetXml(this string @this)
        {
            return XElement.Parse(@this);
        }

        public static XElement GetXml(this byte[] @this)
        {
            return GetXml(GetText(@this));
        }

        public static void SaveXml(this EmbeddedResource @this, XElement node)
        {
            using (var stream = new MemoryStream())
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(node);
                    writer.Close();
                }
                @this.Data = stream.GetBuffer();
                stream.Close();
            }
        }
    }
}